package com._21cn.framework.utils;

import java.beans.PropertyEditor;
import java.beans.PropertyEditorSupport;
import java.util.Date;

/**
 * DatePropertyEditor 提供<code>Date</code>日期类型的<code>PropertyEditorSupport</code>支持
 */
public class DatePropertyEditor extends PropertyEditorSupport implements PropertyEditor {

	public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
	public static final String CHINESE_DATE_FORMAT = "yyyy-MM-dd";
	public static final String CHINESE_DATE_FORMAT_DOT = "yyyy.MM.dd";
	public static final String TIME_HHMMSS_FORMAT  = "HH:mm:ss";

	private String dateFormat = DEFAULT_DATE_FORMAT;
	private boolean returnDefaultDate = false;

	public DatePropertyEditor() {
	}

	/**
	 * 构造器
	 * @param dateFormat 指定的日期格式，如果是null或"",将采用默认的格式：yyyy-MM-dd HH:mm:ss
	 */
	public DatePropertyEditor(String dateFormat) {
		if (StringUtil.isEmpty(dateFormat))
			dateFormat = DEFAULT_DATE_FORMAT;
		this.dateFormat = dateFormat;
	}

	public void setReturnDefaultDate(boolean b){
		this.returnDefaultDate = b;
	}

	public String getAsText() {
		Date value = (Date) getValue();
		if (null == value) {
			if( !returnDefaultDate )
				return "";
			value = new Date();
		}
		return DateUtil.formatDate(value, dateFormat);
	}

	public void setAsText(String text) throws IllegalArgumentException {
		Date value = null;
		if (null != text && !text.equals("")) {
			try {
				value = DateUtil.parseDate( text, dateFormat );
				if( value == null ){
					if( text.matches( "\\d{4}-\\d{2}-\\d{2}" ) ){
						value = DateUtil.parseDate(text, CHINESE_DATE_FORMAT );
					}
					else if( text.matches( "\\d{4}\\.\\d{2}\\.\\d{2}" ) ){
						value = DateUtil.parseDate(text, CHINESE_DATE_FORMAT_DOT );
					}
					else if( text.matches( "\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}" ) ){
						value = DateUtil.parseDate(text, DEFAULT_DATE_FORMAT );
					}
					else if( text.matches( "\\d{2}:\\d{2}:\\d{2}" ) ){
						value = DateUtil.parseDate(text, TIME_HHMMSS_FORMAT );
					}
				}
			}
			catch (Exception e) {
				e.printStackTrace();
			}
		}
		if( value == null && returnDefaultDate )
			value = new Date();
		setValue(value);
	}

}
